package com.example.springboot.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.Mapper.SpUserMapper;
import com.example.springboot.UserSerive.UserService;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.pojo.InUser;
import com.example.springboot.pojo.SpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    //new SpUserMapper
//    @Autowired
//    private SpUserMapper spUserMapper;
    @Autowired
    private UserService userService;
//查
    @GetMapping
    public List<SpUser> index(){
       return userService.list();
    }
    //新增与更新
    @PostMapping
    public boolean saveUser(@RequestBody SpUser spUser){
       //return spUserMapper.in(spUser);
        return userService.saveOrUpdate(spUser);//plus
    }
//删
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id){
        //return spUserMapper.deleteId(id);
        return userService.removeById(id);
    }
//多删除  /{id}只能有一个参数
    @DeleteMapping("/all")
    public boolean deleteAll(@RequestBody List<Integer> ids){
        //return spUserMapper.deleteId(id);
        return userService.removeByIds(ids);
    }

    //分页

//    @GetMapping("/page")
//    public  Map<String,Object> Page(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String username){
//        pageNum=(pageNum-1)*pageSize;
//        username="%"+username+"%";
//        List<SpUser> data=spUserMapper.selectPage(pageNum,pageSize,username);
//        Integer total=spUserMapper.selectToal();
//        Map<String,Object> res=new HashMap<>();
//        res.put("data",data);
//        res.put("total",total);
//       return res;
//    }

//分页plus

    @GetMapping("/page")
    public  IPage<SpUser> Page(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String phone,
                               @RequestParam(defaultValue = "") String address){

        IPage<SpUser> page=new Page<>(pageNum,pageSize);
        QueryWrapper<SpUser> queryWrapper=new QueryWrapper<>();
        if(!"".equals(username)){queryWrapper.like("username",username);}
        if(!"".equals(phone)){queryWrapper.like("phone",phone);}
        if(!"".equals(address)){queryWrapper.like("address",address);}
        queryWrapper.orderByDesc("id");
        return  userService.page(page,queryWrapper);
    }



    //出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<SpUser> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

//入
@PostMapping("/import")
public Boolean imp(MultipartFile file) throws Exception {
    InputStream inputStream = file.getInputStream();
    ExcelReader reader = ExcelUtil.getReader(inputStream);
    reader.addHeaderAlias("用户名","username");
    reader.addHeaderAlias("密码","password");
    reader.addHeaderAlias("昵称","nickname");
    reader.addHeaderAlias("用户名","username");
    reader.addHeaderAlias("邮箱", "email");
    reader.addHeaderAlias("电话", "phone");
    reader.addHeaderAlias("地址", "address");
    reader.addHeaderAlias("创建时间", "createTime");
    reader.addHeaderAlias("头像", "avatarUrl");
    List<SpUser> list = reader.readAll(SpUser.class);
    userService.saveBatch(list);
    return true;
}

@PostMapping("/login")
    public Result login(@RequestBody InUser inUser){
        String username=inUser.getUsername();
        String password=inUser.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        InUser in=userService.login(inUser);
        return Result.success(in);
}
    //注
    @PostMapping("/register")
    public Result register(@RequestBody InUser inUser){
        String username=inUser.getUsername();
        String password=inUser.getPassword();
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
       return  Result.success(userService.register(inUser));
    }



    @GetMapping("/username/{username}")
    public SpUser findone(@PathVariable String username){
        QueryWrapper<SpUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return userService.getOne(queryWrapper);
    }
}
